package com.atguigu.gmall.wms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.atguigu.gmall.wms.vo.SkuLockVo;
import io.lettuce.core.RedisClient;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.wms.mapper.WmsWareSkuMapper;
import com.atguigu.gmall.wms.entity.WmsWareSkuEntity;
import com.atguigu.gmall.wms.service.WmsWareSkuService;
import org.springframework.util.CollectionUtils;


@Service("wmsWareSkuService")
public class WmsWareSkuServiceImpl extends ServiceImpl<WmsWareSkuMapper, WmsWareSkuEntity> implements WmsWareSkuService {

    @Autowired
    WmsWareSkuMapper wmsWareSkuMapper;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    private final static String STOCK_WARE = "stock:ware:";
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<WmsWareSkuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<WmsWareSkuEntity>()
        );

        return new PageResultVo(page);
    }
    /*
    锁库存
     */

    @Override
    public List<SkuLockVo> checkLock(List<SkuLockVo> skuLockVos,String orderToken) {

        // 遍历每个sku属性
        skuLockVos.forEach(item->{
            checkAndLock(item);
        });
        //解锁库存  如果有一个锁库存不成功
        boolean match = skuLockVos.stream().anyMatch(item -> item.getLock() == false);
        if (match){
            //解锁
            skuLockVos.stream().filter(SkuLockVo::getLock).collect(Collectors.toList()).forEach(item->{
                wmsWareSkuMapper.unLock(item.getSkuId(),item.getWareId(),item.getCount());
            });
            //锁定失败
            return skuLockVos;
        }
        redisTemplate.opsForValue().set(STOCK_WARE+orderToken, JSON.toJSONString(skuLockVos));
        //定时解锁库存
        rabbitTemplate.convertAndSend("ORDER_EXCHANGE","stock.ttl.order",orderToken);
        //锁定成功 返回努力
        return null;
    }

    private void checkAndLock(SkuLockVo item) {
        RLock lock = redissonClient.getLock(STOCK_WARE + item.getSkuId());
        lock.lock();
        try {
            //获取该商品的购买数量大于残仓库数量
            List<WareSkuEntity> wareSkuEntities = wmsWareSkuMapper.getSkuWare(item.getSkuId(),item.getCount());
            if (CollectionUtils.isEmpty(wareSkuEntities)){
                item.setLock(false);
            }
            //锁库存 获取第一个库存
            WareSkuEntity wareSkuEntity = wareSkuEntities.get(0);
            if (wmsWareSkuMapper.lock(item.getSkuId(),item.getCount(),wareSkuEntity.getId())==1){
                item.setLock(true);
                item.setWareId(wareSkuEntity.getId());
            }else {
                item.setLock(false);
            }
        } finally {
            lock.unlock();
        }


    }

}